package com.demp2;

import org.apache.poi.ss.usermodel.*;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ExcelImageExtractor {

    public static List<YanHuaInfo> readExcelData(String excelFilePath) {
        List<YanHuaInfo> yanHuaInfoList = new ArrayList<>();
        
        try (InputStream inp = new FileInputStream(excelFilePath);
             Workbook workbook = WorkbookFactory.create(inp)) {

            Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
            List<? extends PictureData> pictures = workbook.getAllPictures();
            
            // 从第二行开始读取（假设第一行是表头）
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (row == null) continue;

                YanHuaInfo info = new YanHuaInfo();
                
                // 读取ID
                Cell idCell = row.getCell(0);
                info.setId(getCellValueAsString(idCell));
                
                // 读取产品名称
                Cell nameCell = row.getCell(1);
                info.setProductName(getCellValueAsString(nameCell));
                
                // 读取图片
                // 假设第三列的图片与pictures列表中的索引对应
                if (rowNum - 1 < pictures.size()) {
                    PictureData pictureData = pictures.get(rowNum - 1);
                    info.setProductImage(pictureData.getData());
                }
                
                // 读取销售类型
                Cell typeCell = row.getCell(3);
                info.setSaleTypes(getCellValueAsString(typeCell));
                
                yanHuaInfoList.add(info);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return yanHuaInfoList;
    }

    private static String getCellValueAsString(Cell cell) {
        if (cell == null) return "";
        
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue();
            case NUMERIC:
                return String.valueOf(cell.getNumericCellValue());
            case BOOLEAN:
                return String.valueOf(cell.getBooleanCellValue());
            default:
                return "";
        }
    }

    public static void main(String[] args) {
        String excelFilePath = "C:\\Users\\wy\\Desktop\\新建 XLSX 工作表.xlsx";
        List<YanHuaInfo> yanHuaInfoList = readExcelData(excelFilePath);
        
        // 打印读取到的数据
        for (YanHuaInfo info : yanHuaInfoList) {
            System.out.println("ID: " + info.getId());
            System.out.println("产品名称: " + info.getProductName());
            System.out.println("图片大小: " + (info.getProductImage() != null ? info.getProductImage().length : 0) + " bytes");
            System.out.println("销售类型: " + info.getSaleTypes());
            System.out.println("------------------------");
        }
    }
}
